import { CacheEnum } from '@/enum/cacheEnum';
import { RouterEnum } from '@/enum/routerEnum';
import customStorage from '@/hooks/useStorage';
import type { RouteLocationNormalized, Router } from 'vue-router';

/**
 * 配置路由导航守卫
 */
class Gurad {
  constructor(private router: Router) {}

  public run() {
    this.router.beforeEach(this.beforeEach.bind(this));
  }

  private async beforeEach(to: RouteLocationNormalized, from: RouteLocationNormalized) {
    // 且未登录，则跳转登录页
    if (this.isLogin(to)) {
      customStorage.setItem(CacheEnum.REDIRECT_ROUTE_NAME, to.name);
      return { name: RouterEnum.LOGIN };
    }
  }

  // 是否需要登录
  private isLogin(to: RouteLocationNormalized) {
    return to.meta.auth && !this.token();
  }

  private token(): string | null {
    return customStorage.getItem(CacheEnum.TOKEN_NAME);
  }
}

const setupGurad = (router: Router) => {
  new Gurad(router).run();
};

export default setupGurad;
